﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            cleanButton.Enabled = false;
            uninstallButton.Enabled = false;
            checkAll.Enabled = false;
            uncheckAll.Enabled = false;
        }



        private void cleanButton_Click(object sender, EventArgs e)
        {
            string sourcePath = Environment.GetEnvironmentVariable("TMP");
            int initCount = listView2.Items.Count;
            ClearFolder(sourcePath);
            listView2.Items.Clear();
            DirSearchAndDisplay(sourcePath);
            int endCount = listView2.Items.Count;
            int removedCount = initCount - endCount;
            if (endCount > 0)
            {
                cleanButton.Enabled = true;
                checkAll.Enabled = true;
                MessageBox.Show("CLEAN UP SUCCESSFUL! \n"+ removedCount +" file(s) were removed. \nSome files cannot be deleted because they are currently being used by other program.",
                                "Information - G4 Uninstaller", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            else
            {
                cleanButton.Enabled = false;
                checkAll.Enabled = false;
                uncheckAll.Enabled = false;
                MessageBox.Show("CLEAN UP SUCCESSFUL! \n" + removedCount + " file(s) were removed.", "Information - G4 Uninstaller", MessageBoxButtons.OK, 
                                MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }

        private void ClearFolder(string sourcePath)
        {
            foreach (ListViewItem item in listView2.CheckedItems)
            {
                try
                {
                    string filepath = item.SubItems[2].Text;
                    File.Delete(filepath);
                }
                catch (UnauthorizedAccessException)
                {
                    //skip file
                }
                catch (ArgumentOutOfRangeException)
                {
                    //skip file
                }
                catch (IOException)
                {
                    //skip file
                }
                catch (Exception)
                {
                    //skip file
                }
            }

            foreach (var directory in Directory.GetDirectories(sourcePath))
            {
                try
                {
                    ClearFolder(directory);
                    if (Directory.GetFiles(directory).Length == 0 &&
                        Directory.GetDirectories(directory).Length == 0)
                    {
                        Directory.Delete(directory, false);
                    }
                }
                catch (IOException)
                {
                    //skip directory
                }
                catch (Exception)
                {
                    //skip directory
                }
            }
        }

        private void tempFilesButton_Click_1(object sender, EventArgs e)
        {
            listView2.Items.Clear();
            string sourcePath = Environment.GetEnvironmentVariable("TMP");
            this.DirSearchAndDisplay(sourcePath);
            checkAllItems();
            if (listView2.Items.Count > 0)
            {
                cleanButton.Enabled = true;
                uncheckAll.Enabled = true;
            }
        }

        private void DirSearchAndDisplay(string sDir)
        {
            cleanButton.Enabled = false;
            string[] tempFiles = new string[3];
            DirectoryInfo dir = new DirectoryInfo(sDir);
            try
            {
                foreach (FileInfo files in dir.GetFiles())
                {
                    tempFiles[0] = files.Name.ToString();
                    tempFiles[1] = files.Length.ToString();
                    tempFiles[2] = files.FullName.ToUpper();
                    listView2.Items.Add(new ListViewItem(tempFiles));
                }

                foreach (string directory in Directory.GetDirectories(sDir))
                {
                    this.DirSearchAndDisplay(directory);
                }
            }
            catch (System.Exception ex)
            {
                listView2.Items.Add(ex.Message);
            }
        }

        private void checkAllItems() 
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = true;
            }
        }

        private void uncheckAllItems()
        {
            for (int i = 0; i < listView2.Items.Count; i++)
            {
                listView2.Items[i].Checked = false;
            }
        }

        private void uninstallButton_Click(object sender, EventArgs e)
        {
            DialogResult dr =  MessageBox.Show("Are you sure you want to uninstall this item?", "Confirmation - G4 Uninstaller",
                                 MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {

                string uninstallStr = listView1.SelectedItems[0].SubItems[3].Text;
                string displayName = listView1.SelectedItems[0].SubItems[0].Text;
                ExecuteUninstallString(uninstallStr);
                listView1.Items.Clear();
                Installed();
                if (isSuccessful(displayName) == true)
                {
                    MessageBox.Show(displayName + " has been successfully uninstalled", "Information - G4 Uninstaller",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    MessageBox.Show(displayName + " was not successfully uninstalled", "Information - G4 Uninstaller",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
            
        }

        private void ExecuteUninstallString(object command)
        {
            try
            {
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                procStartInfo.CreateNoWindow = true;
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = procStartInfo;
                process.Start();
                process.WaitForExit();
                //string log = process.StandardOutput.ReadToEnd();
            }
            catch (Exception)
            {
            }
        }

        private bool isSuccessful(string displayName)
        {
            bool successful = true;
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].SubItems[0].Text == displayName)
                {
                    successful = false;
                }
            }
            return successful;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            uninstallButton.Enabled = true;
        }

        private void Installed()
        {
            string[] Software = new string[4];

            string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
            {

                foreach (string skName in rk.GetSubKeyNames())
                {
                    using (RegistryKey sk = rk.OpenSubKey(skName))
                    {
                        try
                        {

                            if (!(sk.GetValue("DisplayName") == null))
                            {
                                Software[0] = sk.GetValue("DisplayName").ToString();
                                Software[1] = sk.GetValue("Publisher").ToString();
                                Software[2] = sk.GetValue("InstallLocation").ToString();
                                Software[3] = sk.GetValue("UninstallString").ToString();
                                listView1.Items.Add(new ListViewItem(Software));
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            uninstallButton.Enabled = false;
            Installed();
        }


        private void checkAll_Click(object sender, EventArgs e)
        {
            checkAllItems();
            checkAll.Enabled = false;
            uncheckAll.Enabled = true;
            cleanButton.Enabled = true;
        }

        private void uncheckAll_Click(object sender, EventArgs e)
        {
            uncheckAllItems();
            uncheckAll.Enabled = false;
            checkAll.Enabled = true;
            cleanButton.Enabled = false;
        }

        private void listView2_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            checkAll.Enabled = true;
            uncheckAll.Enabled = true;
            if (listView2.CheckedItems.Count > 0)
            {
                cleanButton.Enabled = true;
            }
            else
            {
                cleanButton.Enabled = false;
                uncheckAll.Enabled = false;
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            uninstallButton.Enabled = true;
        }

        private void about_Click(object sender, EventArgs e)
        {
            AboutBoxG4 about = new AboutBoxG4();
            about.ShowDialog();
        }
    }
}
